'''
Created on 18/ago/2010

@author: stefano
'''

import gtk.glade #@UnresolvedImport
import pygtk #@UnresolvedImport
import gobject #@UnresolvedImport
import DataParser
import pyF1Classes


def on_FantaF1_destroy(widget, data=None):
    gtk.main_quit()

def on_btnExit_clicked(widget, data=None):
    gtk.main_quit()
    
def on_cbTeam_changed(widget, data=None):
    updateMoney()    
    
def on_btnAdd_clicked(widget, data=None):
    addPilot()

def on_btnRemove_clicked(widget, data=None):
    removePilot()

def on_btnRemoveAll_clicked(widget, data=None):
    removeAllPilot()

def on_btnInvia_clicked(widget, data=None):
    print("invia formazione")

def fillTeamList():
    modelCombo = gtk.ListStore(gobject.TYPE_STRING)
    
    for k in range(len(keyTeam)):
        modelCombo.append([keyTeam[k].getKey()])
    
    cbTeam.set_model (modelCombo)
    cell = gtk.CellRendererText()
    cbTeam.pack_start(cell, True)
    cbTeam.add_attribute(cell, 'text',0)

def fillPilotList():
    cella = gtk.CellRendererText()
    colonna0 = gtk.TreeViewColumn("Nome", cella, text=0)  
    colonna1 = gtk.TreeViewColumn("Team", cella, text=1)  
    colonna2 = gtk.TreeViewColumn("Prezzo", cella, text=2)  
    
    # Append delle colonne:  
    tvPilots.append_column(colonna0)  
    tvPilots.append_column(colonna1)  
    tvPilots.append_column(colonna2)  
       
    # Colonne allargabili:  
    colonna0.set_resizable(True)  
    colonna1.set_resizable(True)  
    colonna2.set_resizable(True)  
    
    store = gtk.TreeStore(gobject.TYPE_STRING)  
    tvPilots.set_model(store)
    tvPilots.set_reorderable(True)  
  
    # Gestione Tabella
    modelTree = gtk.ListStore (str, str, int)
    for k in range(len(keyPilota)):
        modelTree.append([keyPilota[k].getNominativo(), keyPilota[k].scuderia, int(keyPilota[k].prezzo)])
          
    tvPilots.set_model(modelTree)

def initSelectedPilotList():
    cella = gtk.CellRendererText()
    colonna0 = gtk.TreeViewColumn("Nome", cella, text=0)  
    colonna1 = gtk.TreeViewColumn("Team", cella, text=1)  
    colonna2 = gtk.TreeViewColumn("Prezzo", cella, text=2)  
    
    # Append delle colonne:  
    tvSelectedPilots.append_column(colonna0)  
    tvSelectedPilots.append_column(colonna1)  
    tvSelectedPilots.append_column(colonna2)  
       
    # Colonne allargabili:  
    colonna0.set_resizable(True)  
    colonna1.set_resizable(True)  
    colonna2.set_resizable(True)  
    
    store = gtk.TreeStore(gobject.TYPE_STRING)  
    tvSelectedPilots.set_model(store)
    tvSelectedPilots.set_reorderable(True)  
  
    # Gestione Tabella
    modelTree = gtk.ListStore (str, str, int)
    for k in range(len(savedPilots)):
        modelTree.append([savedPilots[k].getNominativo(), savedPilots[k].scuderia, int(savedPilots[k].prezzo)])
          
    tvSelectedPilots.set_model(modelTree)

def addSavedPilots():
    for i in range(6):
        savedPilots.append(pyF1Classes.Pilot("-","-","-","-",0))
        
def modifySavedPilots():
    pass

def addToList1():
    pass

def removeFromList1():
    pass

def addToList2():
    pass

def removeFromList2():
    pass

def addPilot():
    allowed, index = checkSelectedPilot()
    if allowed:
        treeSelection = tvPilots.get_selection()
        model, iter = treeSelection.get_selected()
        SelPilotModel = tvSelectedPilots.get_model()
        if iter:
            SelPilotModel[index] = (model.get_value(iter,0),model.get_value(iter,1),model.get_value(iter,2))
            model.remove(iter)
        updateMoney()
    
        
def removePilot():
    treeSelection = tvSelectedPilots.get_selection()
    model, iter = treeSelection.get_selected()
    #Se il pilota scelto e' "--" non fare nulla
    if model.get_value(iter,0) == "- -":
        print("Il campo selezionato e' vuoto!")
        return 0
    #Dopo aver rimosso sostituire con "- -"
    pilotModel = tvPilots.get_model()
    if iter:
        pilotModel.append([model.get_value(iter,0),model.get_value(iter,1),model.get_value(iter,2)])
        model.set_value(iter,0,"- -")
        model.set_value(iter,1,"-")
        model.set_value(iter,2,0)
    updateMoney()


def removeAllPilot():
    selectedPilotsModel = tvSelectedPilots.get_model()
    #Dopo aver rimosso sostituire con "- -"
    pilotModel = tvPilots.get_model()
    for i in range(6):
        myIter = selectedPilotsModel.get_iter(i)
        if selectedPilotsModel.get_value(myIter,0) != "- -":
            pilotModel.append([selectedPilotsModel.get_value(myIter,0),selectedPilotsModel.get_value(myIter,1),selectedPilotsModel.get_value(myIter,2)])
            selectedPilotsModel.set_value(myIter,0,"- -")
            selectedPilotsModel.set_value(myIter,1,"-")
            selectedPilotsModel.set_value(myIter,2,0)
    updateMoney()

def checkSelectedPilot():
    allowSelection = False
    selectedPilots = tvSelectedPilots.get_model()
    for i in range(len(selectedPilots)):
        myIter = selectedPilots.get_iter(i)
        if selectedPilots.get_value(myIter,0) == "- -":
            allowSelection = True
            break
    return allowSelection, i

def updateMoney():
    selectedPilotsModel = tvSelectedPilots.get_model()
    price = [0,0,0,0,0,0,0]
    moneyValue.valore = 1000
    for i in range(6):
        myIter = selectedPilotsModel.get_iter(i)
        myValue = selectedPilotsModel.get_value(myIter,2)
        price[i] = myValue
        print(myValue)
        moneyValue.valore = moneyValue.valore - myValue
    
    k = cbTeam.get_active()
    if k != -1:
        price[6] = int(keyTeam[k].prezzo)
    else:
        price[6] = 0
    
    moneyValue.valore = moneyValue.valore - price[6]
    print(price,moneyValue.valore)
    
    #stringaLabel = "<b><big>"+str(valoreFondi.valore)+"</big></b>"
    stringaLabel = str(moneyValue.valore)
    stringaNoFondi = "!! " + stringaLabel + " Non hai abbastanza fondi !!"
    print stringaLabel
    
    if moneyValue.valore < 0:
        lbMoney.set_label("<b><big>%s</big></b>" % stringaNoFondi)
    else:
        lbMoney.set_label("<b><big>%s</big></b>" % stringaLabel)


segnali = {
    'on_FantaF1_destroy': on_FantaF1_destroy,
    'on_btnExit_clicked': on_btnExit_clicked,
    'on_cbTeam_changed': on_cbTeam_changed,
    'on_btnAdd_clicked': on_btnAdd_clicked,
    'on_btnRemove_clicked': on_btnRemove_clicked,
    'on_btnRemoveAll_clicked': on_btnRemoveAll_clicked,
    'on_btnInvia_clicked': on_btnInvia_clicked
}

#dialog
gladeFile = gtk.glade.XML('PyFF1.glade')
FantaF1 = gladeFile.get_widget('FantaF1')

#pulsanti
btnExit = gladeFile.get_widget('btnExit')
btnHelp = gladeFile.get_widget('btnHelp')
btnAdd = gladeFile.get_widget('btnAdd')
btnRemove = gladeFile.get_widget('btnRemove')
btnRemoveAll = gladeFile.get_widget('btnRemoveAll')
btnInvia = gladeFile.get_widget('btnInvia')

#treeview
tvPilots = gladeFile.get_widget('tvPilots')
tvSelectedPilots = gladeFile.get_widget('tvSelectedPilots')

#combobox
cbTeam = gladeFile.get_widget('cbTeam')

#labels
lbMoney = gladeFile.get_widget("lbMoney")

gladeFile.signal_autoconnect(segnali)

# ---------------------------------------

#keyPilota, keyTeam = DataParser.FileParsing() # recupero i dati dai file su PC
keyPilota, keyTeam = DataParser.DataParsing() # recupero i dati dal Web
moneyValue = pyF1Classes.Fondi(1000)
savedPilots = []
addSavedPilots()
fillTeamList()  # riempio la combo box
fillPilotList() # riempio la treeview con tutti i piloti
initSelectedPilotList() # inizializzo una lista vuota per i piloti selezionati

if FantaF1:
        
    FantaF1.show()
    gtk.main()
